#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <SDL2/SDL.h>
#include <QFile>

#define END(conditon,func)  if(conditon) {\
    qDebug() << #func << "error";\
    goto end;\
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{

    int width = 512;
    int height = width;
    SDL_Window* window = nullptr;
    SDL_Renderer* renderer = nullptr;
    SDL_Texture* texture = nullptr;
    SDL_Event event;
    char* yuvPath = "/Users/tgy/Documents/ffmpeg/image/demo.yuv";

    QFile file(yuvPath);

    END(SDL_Init(SDL_INIT_VIDEO),SDL_Init);

    window = SDL_CreateWindow("显示yuv",SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,width,height,SDL_WINDOW_SHOWN);

    END(!window,SDL_CreateWindow);



   renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC);

   if(!renderer) {

       renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_SOFTWARE);
   }

   END(!renderer,SDL_CreateRenderer);
    // SDL_PIXELFORMAT_IYUV == YUV420p
   texture = SDL_CreateTexture(renderer,SDL_PIXELFORMAT_IYUV,0,width,height);

   END(!texture,SDL_CreateTexture);


   END(!file.open(QFile::ReadOnly),fileOpen);

   // yuv update texture
   END(SDL_UpdateTexture(texture,nullptr,file.readAll(),width),SDL_UpdateTexture);

   SDL_SetRenderDrawColor(renderer,0,0,0,255);

   SDL_RenderClear(renderer);

   SDL_RenderCopy(renderer,texture,nullptr,nullptr);

   SDL_RenderPresent(renderer);


   while(true) {

       SDL_WaitEvent(&event);

       if(event.type == SDL_QUIT) {

           break;
       }

   }


end:
   SDL_DestroyTexture(texture);
   SDL_DestroyWindow(window);
   SDL_DestroyRenderer(renderer);
    SDL_Quit();

}
